package io.gitee.zicai.graphql.sample.self.fetcher;

import graphql.schema.DataFetcher;
import io.gitee.zicai.graphql.sample.dao.MajorRepo;
import io.gitee.zicai.graphql.sample.entity.Major;
import io.gitee.zicai.graphql.sample.entity.QMajor;
import io.gitee.zicai.graphql.sample.self.GraphQLBaseDataFetcher;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * MajorDataFetcher
 *
 * @author zicai
 * @since 2021-03-09
 */
@Component
public class MajorDataFetcher extends GraphQLBaseDataFetcher<MajorRepo, Major, String> {

    public DataFetcher<List<Major>> queryByName() {
        return env -> {
            String name = env.getArgument("name");
            return this.findAll(QMajor.major.name.like("%" + name + "%"));
        };
    }

    public DataFetcher<Major> updateById() {
        return env -> {
            String id = env.getArgument("id");
            String name = env.getArgument("name");
            String classRoom = env.getArgument("classRoom");

            return dao.findById(id)
                    .map(o -> o.setName(name).setClassRoom(classRoom))
                    .map(dao::saveAndFlush)
                    .orElse(null);
        };
    }

    public DataFetcher<Major> save() {
        return env -> {
            String name = env.getArgument("name");
            String classRoom = env.getArgument("classRoom");

            Major Major = new Major().setName(name).setClassRoom(classRoom);
            return dao.saveAndFlush(Major);
        };
    }

}
